package com.aimei520.controller.intercepter;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import com.aimei520.mapper.LogMapper;
import com.aimei520.po.admin.Log;
import com.aimei520.po.admin.Url;
import com.aimei520.po.admin.User;

/**
 * log--日志记录
 * Title: LoginInterceptor.java
 * Description:  
 * Copyright: Copyright (c) 2018
 * Company: www.storyboy.xyz 
 * @author JiaXun  
 * @date 2018年9月6日  
 * @version 1.0.0
 */
public class LogInterceptor extends HandlerInterceptorAdapter{

	private UrlPathHelper helper = new UrlPathHelper();
	
	@Resource
	private LogMapper logMapper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String url = helper.getLookupPathForRequest(request);
		User user = (User)request.getSession().getAttribute("user");
		List<Url> urls = (List<Url>)request.getSession().getAttribute("url");
		
		String message = unionMessage(user.getName(), user.getUsername(), url, urls);
		
		Log log= new Log();
		log.setIp( getClientIp(request) );
		log.setUserId(user.getId());
		log.setCreatetime(new Date());
		log.setMessage(message);
		
		logMapper.addLog(log);
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}

	private String unionMessage(String name,String username,String url,List<Url> urls ) {
		StringBuffer resultBuffer = new StringBuffer();
		resultBuffer.append("操作员："+name);
		resultBuffer.append(",登录账号："+username);
		resultBuffer.append(",操作地址："+url);
		resultBuffer.append(",操作方法："+urlTitle(url,urls));
		
		return new String(resultBuffer);
	}
	
	private String urlTitle(String url ,List<Url> urls) {
		
		for (Url url2 : urls) {
			if(url2.getUrl().equals(url)) {
				return url2.getTitle();
			}
		}
		
		return "未知";
	}
	
	private static String getClientIp( HttpServletRequest request) {

        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }
	
}
